// import encoding from '@/static/encoding.js'

let encoding = require('@/static/js/encoding.js')


export function buf2hex(arrayBuffer) {
	return Array.prototype.map.call(new Uint8Array(arrayBuffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}

/**
* 十六进制字符串转中文
* @param {String} hex 为十六进制字符串
* @return {String} 包含中文的字符串
*/
export function hexToStr(hex) {
	// 去掉字符串首尾空格
	let trimedStr = hex.trim()
	// 判断trimedStr前两个字符是否为0x，如果是则截取从第三个字符及后面所有，否则返回全部字符
	let rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr
	// 得到rawStr的长度
	let len = rawStr.length
	// 如果长度不能被2整除，那么传入的十六进制值有误，返回空字符
	if (len % 2 !== 0) {
		return ""
	}
	let curCharCode // 接收每次循环得到的字符
	let resultStr = [] // 存转换后的十进制值数组
	for (let i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16)
		resultStr.push(curCharCode)
	}
	// encoding为空时默认为utf-8
	let bytesView = new Uint8Array(resultStr) // 8 位无符号整数值的类型化数组
	// TextEncoder和TextDecoder对字符串和字节流互转  
	// let str = new TextDecoder(encoding).decode(bytesView)因为小程序中没有TextDecoder,经查阅资料，下载https://github.com/inexorabletash/text-encoding并const encoding = require("./text-encoding-master/lib/encoding.js")引入后使用下面方式即可：
	let str = new encoding.TextDecoder("gbk").decode(bytesView)
	return str
}

export function decodeUtf8(temp){
	return new encoding.TextDecoder("utf-8").decode(temp)
}

export function arrayBufferToString(arr){
    if(typeof arr === 'string') {  
        return arr;  
    }  
    var dataview=new DataView(arr.data);
    var ints=new Uint8Array(arr.data.byteLength);
    for(var i=0;i<ints.length;i++){
      ints[i]=dataview.getUint8(i);
    }
    arr=ints;
    var str = '',  
        _arr = arr;  
    for(var i = 0; i < _arr.length; i++) {  
        var one = _arr[i].toString(2),  
            v = one.match(/^1+?(?=0)/);  
        if(v && one.length == 8) {  
            var bytesLength = v[0].length;  
            var store = _arr[i].toString(2).slice(7 - bytesLength);  
            for(var st = 1; st < bytesLength; st++) {  
                store += _arr[st + i].toString(2).slice(2);  
            }  
            str += String.fromCharCode(parseInt(store, 2));  
            i += bytesLength - 1;  
        } else {  
            str += String.fromCharCode(_arr[i]);  
        }  
    }  
    return str;
}